package m202311.d07;

/**
 * @author haocongshun
 * @date 2023/11/07 19:43:45
 */

import java.util.Arrays;
import java.util.HashSet;

/**
 * 202. 快乐数
 */
public class Q202 {
    public boolean isHappy(int n) {
        HashSet<Integer> history = new HashSet<>();
        while (n != 1 && !history.contains(n)) {
            history.add(n);
            n = calc(n);
        }
        return n == 1;
    }

    public int calc(int n) {
        int result = 0;
        String s = String.valueOf(n);
        for (int i = 0; i < s.length(); i++) {
            int e = s.charAt(i) - '0';
            result = result + e * e;
        }
        return result;
    }
}
